package com.baiduspring.dubbo.service.server.user;

import com.baiduspring.dao.entity.User;
import com.baiduspring.dao.mapper.UserMapper;
import com.baiduspring.dao.mapper.params.UserParam;
import com.baiduspring.error.BaiduSpringException;
import com.baiduspring.service.user.UserService;
import com.baiduspring.service.virtualnum.VirtualNumberService;
import com.baiduspring.utils.security.SystemSecurityEncrypt;
import com.baiduspring.vo.UserVO;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Optional;

/**
 * 用户相关接口实现类
 *
 * @author xiongyan
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private VirtualNumberService virtualNumberService;

    /**
     * 用户注册接口
     *
     * @param userVO 参数
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(UserVO userVO) {
        User user = userVO.validate().conver(userVO, new User());

        Integer count = userMapper.uniqueness(user);
        String phoneMsg = "电话号码：";
        String exist = "，已经存在";
        if (count > 0) {
            throw new BaiduSpringException(phoneMsg + user.getPhoneNumber() + exist);
        }

        Long account = virtualNumberService.getVirtualNumber();
        Preconditions.checkArgument(Objects.nonNull(account), "虚拟账号获取失败");

        user.setAccount(account);

        userMapper.insertSelective(user);
    }

    /**
     * 用户登录接口
     *
     * @param name     用户名
     * @param password 密码
     * @return 返回登录用户信息
     */
    @Override
    public Optional<User> login(String name, String password) {
        Preconditions.checkArgument(!StringUtils.isEmpty(name), "用户名不能为空");
        Preconditions.checkArgument(!StringUtils.isEmpty(password), "用户名不能为空");

        UserParam userParam = new UserParam();
        userParam.setName(name);

        User user = userMapper.selectByName(userParam);
        String userNameEmpty = "用户名不存在";
        if (Objects.isNull(user)) {
            throw new BaiduSpringException(userNameEmpty);
        }

        userParam.setPassword(SystemSecurityEncrypt.encrypt(password));
        user = userMapper.selectByNameAndPassword(userParam);
        String pwdError = "用户名或密码不正确";
        if (Objects.isNull(user)) {
            throw new BaiduSpringException(pwdError);
        }

        return Optional.ofNullable(user);
    }

    /**
     * 验证账号的唯一性。
     * 可以是：手机号码、用户名和邮箱
     *
     * @param name 账号
     * @return 返回user对象
     */
    @Override
    public Optional<User> uniqueness(String name) {
        Preconditions.checkArgument(!StringUtils.isEmpty(name), "账号不能为空");
        UserParam userParam = new UserParam();
        userParam.setName(name);
        return Optional.ofNullable(userMapper.selectByName(userParam));
    }

    @Override
    public Optional<User> getByAccount(Long account) {
        return Optional.ofNullable(userMapper.selectByAccount(account));
    }

    @Override
    public int modifyHomepageViewsByAccount(Long account) {
        return userMapper.updateHomepageViewsByAccount(account);
    }

    @Override
    public void modifyPasswordByMobile(String mobile, String newPassword) {
        try {
            userMapper.updatePasswordByMobile(mobile, SystemSecurityEncrypt.encrypt(newPassword));
        } catch (BaiduSpringException e) {
            log.error("密码修改错误：{}", e);
            e.setErrorMsg("密码修改失败");
            throw e;
        }
    }

    @Override
    public void saveUserPhoto(Long id, String photo) {
        User user = new User();
        user.setId(id);
        user.setPhoto(photo);
        try {
            userMapper.updateByPrimaryKeySelective(user);
        } catch (BaiduSpringException e) {
            log.error("保存用户头像信息报错：{}", e);
            e.setErrorMsg("上传失败");
            throw e;
        }
    }
}
